package com.yc.bran.snack.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.bran.snack.bean.Address;
import com.yc.bran.snack.bean.GoodsTypeSales;
import com.yc.bran.snack.bean.OrderInfo;
import com.yc.bran.snack.bean.OrderItemInfo;
import com.yc.bran.snack.dto.OrderInfoDTO;
import com.yc.bran.snack.mapper.IGoodsInfoMapper;
import com.yc.bran.snack.mapper.IOrderInfoMapper;
import com.yc.bran.snack.mapper.IOrderItemInfoMapper;
import com.yc.bran.snack.service.IOrderInfoService;

@Service  
@Transactional
public class OrderInfoServiceImpl implements IOrderInfoService {  

	@Autowired  
	private IOrderInfoMapper orderInfoMapper;  
	
	@Autowired
	private IGoodsInfoMapper goodsInfoMapper;

	@Autowired  
	private IOrderItemInfoMapper orderDetailMapper; 

	@Autowired  
	private StringRedisTemplate redisTemplate; 

	@Autowired  
	private RedisTemplate<String, String> stringredisTemplate;

	@Autowired  
	private ObjectMapper objectMapper;

	private static final String CART_PREFIX = "uid:cart:";

	// 创建订单
	@Override  
	public void createOrder(OrderInfo orderInfo, List<OrderItemInfo> orderItem, Address address) {
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");  
		String datePart = dateFormat.format(new Date());  
		Random random = new Random();  
		int randomPart = random.nextInt(90000) + 10000;
		String ono = datePart + randomPart;
		orderInfo.setOno(ono);  
		orderInfo.setUname(address.getUname());  
		orderInfo.setUtel(address.getUtel());  
		orderInfo.setAddre(address.getAddre());  
		orderInfo.setDetailed(address.getDetailed());

		orderInfoMapper.insertOrderInfo(orderInfo);

		String orderCacheKey = "order:" + orderInfo.getOno();  

		redisTemplate.delete(orderCacheKey);  

		for (OrderItemInfo detail : orderItem) {  
			detail.setOno(orderInfo.getOno());
			
			int gblance = goodsInfoMapper.selectGblance(detail.getGid());
			
			System.out.println(gblance);
			if(gblance != 0 && gblance >= detail.getNum()) {
				Map<String, Object> updateParams = new HashMap<>();  
				updateParams.put("gid", detail.getGid());  
				updateParams.put("newGblance", gblance - detail.getNum());  
				goodsInfoMapper.updateGblance(updateParams);
			}
			
			orderDetailMapper.insertOrderDetail(detail);  
		}
		System.out.println(orderItem);
	}

	// 删除购物车
	public void deleteItemFromCart(String uid, String itemId) {  
		String cartKey = CART_PREFIX + uid;  

		Boolean exists = redisTemplate.opsForHash().hasKey(cartKey, itemId);  
		if (exists) {  
			redisTemplate.opsForHash().delete(cartKey, itemId);  
			System.out.println("商品 " + itemId + " 已从购物车中删除。");  
		} else {  
			System.out.println("购物车中不存在商品 " + itemId + "。");  
		}
	}

	// 查询待发货商品
	@Override
	public List<OrderInfoDTO> pendingOrders(Integer uid) {
		List<OrderInfo> orders = orderInfoMapper.selectOrdersByUid(uid);  
		List<OrderInfoDTO> result = new ArrayList<>();  

		for (OrderInfo orderInfo : orders) {  
			List<OrderItemInfo> orderItems = orderDetailMapper.selectOrdersPending(orderInfo.getOno());  
			OrderInfoDTO orderInfoDTO = new OrderInfoDTO(orderInfo, orderItems);  
			result.add(orderInfoDTO);
		}

		return result;  
	}
	
	// 查询已发货商品
	@Override
	public List<OrderInfoDTO> shippedOrders(Integer uid) {
		List<OrderInfo> orders = orderInfoMapper.selectOrdersByUid(uid);  
		List<OrderInfoDTO> result = new ArrayList<>();  

		for (OrderInfo orderInfo : orders) {  
			List<OrderItemInfo> orderItems = orderDetailMapper.selectOrdersShipped(orderInfo.getOno());  
			OrderInfoDTO orderInfoDTO = new OrderInfoDTO(orderInfo, orderItems);  
			result.add(orderInfoDTO);
		}

		return result;  
	}

	// 当用户取消支付时从reids取出订单数据
	public Map<String, Object> getCancelledOrdersByUid(Integer uid) throws IOException {  
        String key = "cancelled_orders_by_uid:" + uid;  

        Map<Object, Object> rawEntries = redisTemplate.opsForHash().entries(key);  
  
        Map<String, Object> orders = new HashMap<>();  
        for (Map.Entry<Object, Object> entry : rawEntries.entrySet()) {  
            String orderJson = (String) entry.getValue();
            Object orderObject = objectMapper.readValue(orderJson, Object.class);
            orders.put(entry.getKey().toString(), orderObject);
        }  
  
        return orders;  
    }

	@Override
	public List<OrderInfo> selectAllOrder() {
		return orderInfoMapper.selectAllOrder();
	}

	@Override
	public List<OrderItemInfo> selectAllShipped() {
		return orderDetailMapper.selectAllShipped();
	}

	@Override
	public int shipments(Integer gid) {
		return orderDetailMapper.shipments(gid);
	}

	@Override
	public List<GoodsTypeSales> count() {
		return orderDetailMapper.count();
	}

	@Override
	public List<Map<String, Object>> selectMonthlyData() {
		return orderInfoMapper.selectMonthlyData();
	}
  
}
